import { createRouter, createWebHashHistory } from 'vue-router'
import BlogList from '../views/BlogList.vue'
import MyBlogs from '../views/MyBlogs.vue'
import CreateBlog from '../views/CreateBlog.vue'
import EditBlog from '../views/EditBlog.vue'
import BlogDetail from '../views/BlogDetail.vue'

const routes = [
  {
    path: '/',
    name: 'BlogList',
    component: BlogList
  },
  {
    path: '/blogs/:id',
    name: 'BlogDetail',
    component: BlogDetail
  },
  {
    path: '/my-blogs',
    name: 'MyBlogs',
    component: MyBlogs,
    meta: { requiresAuth: true }
  },
  {
    path: '/create',
    name: 'CreateBlog',
    component: CreateBlog,
    meta: { requiresAuth: true }
  },
  {
    path: '/edit/:id',
    name: 'EditBlog',
    component: EditBlog,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      // 打开登录弹窗而不是跳转
      window.showLoginDialog = true
      next(false)
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
